package com.jaydenxiao.androidfire.ui.main.activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.KeyEvent;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import com.jaydenxiao.androidfire.R;

public class WebActivity extends Activity {
    private WebView webView;
    private Dialog dialog;
    private String url, cookies;
    private String roleId = "";
    private static Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    };
    public static int states = 0;
    private String curl = "";
    //配置需要取的权限
    public static String FINISH = "com.action.chucaipz.finish";
    public static String JUMP = "com.action.chucaipz.jump";

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(FINISH)) {
                finish();
            } else if (intent.getAction().equals(JUMP)) {
                String url = intent.getStringExtra("url");
                if (!url.equals(curl)) {
                    webView.loadUrl(url);
                }
                curl = url;
            }
        }
    };

    private void regRec() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(FINISH);
        filter.addAction(JUMP);
        registerReceiver(receiver, filter);
    }

    private void unregisterRec() {
        unregisterReceiver(receiver);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web3);
        states = 1;
//        dialog.show();
        final SwipeRefreshLayout swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                webView.reload();
                swipeRefreshLayout.setRefreshing(false);
            }
        });
//        titleBar.addRightText("关闭", new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                finish();
//            }
//        });


        webView = (WebView) findViewById(R.id.web_view);
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setUseWideViewPort(true);
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webSettings.setAllowFileAccess(true);
        webSettings.setSupportZoom(true);
        webSettings.setDomStorageEnabled(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
//        if (TextUtils.isEmpty(getIntent().getStringExtra("url"))) {
//            url = "http://baike.baidu.com/search/word?word=" + getIntent().getStringExtra("title");
//        } else {
        curl = getIntent().getStringExtra("url");
//        }
//        Toast.makeText(this, url, Toast.LENGTH_SHORT).show();
//        synCookies(getApplication(), url);

        webView.loadUrl(curl);
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                if (newProgress == 100) {
//                    dialog.dismiss();
                }
            }

        });

        webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
//                super.onReceivedSslError(view, handler, error);
                handler.proceed();
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url.startsWith("http:") || url.startsWith("https:")) {
                    view.loadUrl(url);
                    return false;
                } else {
//                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
//                    startActivity(intent);
                    return true;
                }
            }

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
//                if (AVUser.getCurrentUser() == null) return;
//                if (url.startsWith(APIConstants.HEALTH_URL + AVUser.getCurrentUser().getObjectId()
//                        + "&roleId=") && !control) {
//                    webView.stopLoading();
//                    try {
//                        roleId = url.substring(url.indexOf("roleId=") + 7, url.length());
//                    } catch (Exception e) {
//                        roleId = "";
//                    }
//                    cancelAd();
//                } else control = false;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
//                if (url.startsWith(APIConstants.HEALTH_URL)) {
//                    try {
//                        roleId = url.substring(url.indexOf("roleId=") + 7, url.length());
//                    } catch (Exception e) {
//                        roleId = "";
//                    }
//                    view.loadUrl("javascript:window.handler.show(document.body.innerHTML);");
//                }
                super.onPageFinished(view, url);
            }
        });
//        if (url.startsWith(APIConstants.HEALTH_URL))
//            webView.addJavascriptInterface(new Html(), "handler");
        regRec();
    }


    private boolean control;

    // 退出时间
    private long currentBackPressedTime = 0;
    // 退出间隔
    private static final int BACK_PRESSED_INTERVAL = 1000;


    @Override
    public void onBackPressed() {
        if (webView.canGoBack()) {
            webView.goBack();//返回上一页面
        } else {

            if (System.currentTimeMillis() - currentBackPressedTime > BACK_PRESSED_INTERVAL) {
                currentBackPressedTime = System.currentTimeMillis();
                Toast.makeText(this, "再按一次退出", Toast.LENGTH_SHORT).show();
            } else {
                finish();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
        unregisterRec();
        states = 0;
    }

    public void synCookies(Context context, String url) {
        CookieSyncManager.createInstance(context);
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        cookieManager.removeSessionCookie();//移除
        cookieManager.setCookie(url, cookies);//cookies是在HttpClient中获得的cookie
        CookieSyncManager.getInstance().sync();
    }



}
